

import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { IdfaModel } from 'src/mongodb/models/idfaModel/idfa.models';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { QuDaoApiClass, qudaoEnum } from './idfaapi';
import { InjectModel } from 'nestjs-typegoose';
import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto'
import { QudaotjModel } from 'src/mongodb/models/qudaotjModel/qudaotjModel';
import { RedisdbService } from 'src/redis/redisdb.service';


@Injectable()
export class OperatService extends QuDaoApiClass {
    constructor(
        @InjectModel(QudaobaoModel) private readonly channel: ModelType<QudaobaoModel>,
        @InjectModel(QudaotjModel) private readonly qudaotj: ModelType<QudaotjModel>,
        private redis: RedisdbService
    ) {
        super()
    }


    async methodFun(body, req, mode: "jihuo" | "zhuche" | "fuzhi" | "baomin" | 'tiaozuan') {
        try {

            const channelResult = await this.channel.findOne({ mark: req.dns })

            if (this[qudaoEnum[channelResult.channel]] == 'null') return

            let imeiData = JSON.parse(body.imei)
            /* 安卓用户数据匹配 */
            let result: IdfaModel
            if (body.platform == 'android') {
                if (imeiData.oaid) {
                    result = await this.redis.get(imeiData.oaid.toLowerCase() + "_" + req.dns)
                    if (!result) {
                        if (imeiData.imei) await md5imei.call(this)
                    }
                } else if (imeiData.imei) {
                    await md5imei.call(this)
                }

                async function md5imei() {
                    const imei: string[] = imeiData.imei.split(",")
                    for (let item of imei) {
                        const md5 = crypto.createHash('md5');
                        result = await this.redis.get(md5.update(item).digest('hex') + "_" + req.dns);
                        if (result) break;
                    }
                }
            }

            if (body.platform == 'ios') {
                if (imeiData.idfa) {
                    result = await this.redis.get(imeiData.idfa.toLowerCase() + "_" + req.dns)
                }
            }

            if (body.platform == 'web' && channelResult.webmodel) {
                if (imeiData.ips) {
                    console.log(imeiData.ips);
                    result = await this.redis.get(imeiData.ips + "_" + req.dns)
                }
            }
            // ========================================================
            if (result) {
                /* 查询渠道包对应渠道名 */
                return await this[qudaoEnum[channelResult.channel]](mode, result, this.qudaotj)
            } else {
                console.log(mode + '--未查询到对应数据' + JSON.stringify(body));
            }
        } catch (error) {
            console.log(error);
        }
    }
}



